package 递归;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @PackageName: 递归
 * @ClassName: LeetCode112
 * @Author: chen jinxu
 * @Date: 2022/3/11 22:58
 * 给你二叉树的根节点root 和一个表示目标和的整数targetSum 。判断该树中是否存在 根节点到叶子节点 的路径，这条路径上所有节点值相加等于目标和targetSum 。如果存在，返回 true ；否则，返回 false 。
 * 叶子节点 是指没有子节点的节点。
 */
public class LeetCode112 {
    public static void main(String[] args) {

    }

    /**
     *广度优先搜索
     */
    public static boolean hasPathSum(TreeNode root, int targetSum) {
        if (root == null) {
            return false;
        }
        Queue<TreeNode> queNode = new LinkedList<>();
        Queue<Integer> queVal = new LinkedList<>();
        queNode.offer(root);
        queVal.offer(root.val);
        while (!queNode.isEmpty()) {
            TreeNode nowNode = queNode.poll();
            Integer temp = queVal.poll();
            if (nowNode.left == null && nowNode.right == null) {
                if (temp == targetSum) {
                    return true;
                }
                continue;
            }
            if (nowNode.left != null) {
                TreeNode left = nowNode.left;
                queNode.offer(left);
                queVal.offer(temp + left.val);
            }
            if (nowNode.right != null) {
                TreeNode right = nowNode.right;
                queNode.offer(right);
                queVal.offer(temp + right.val);
            }
        }
        return false;
    }

    //递归
    public static boolean hasPathSum1(TreeNode root, int sum) {
        if (root == null) {
            return false;
        }
        if (root.left == null && root.right == null) {
            return root.val == sum;
        }
        return hasPathSum1(root.left, sum - root.val) || hasPathSum1(root.right, sum - root.val);
    }


    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

}
